<?php
namespace app\api\controller;

use app\common\controller\ApiController;
use think\App;
use think\facade\Db;

class Shop extends ApiController
{
    protected $noNeedLogin = [
        "get_banner_list",
        "listof_influencers_list",
        "get_announcement_list",
        "getanx_type",
        "anx_detail"
    ];
    protected $mustLogin = [];
    protected $counter = 0;

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    //轮播图列表
    public function get_banner_list()
    {
        $param = $this->request->param();
        $num = isset($param['num'])?$param['num']:5;
        $list = Db::name("banner")->order('id desc')->paginate($num);
        $this->success('获取成功', $list);
    }

     //公告分类列表
     public function getanx_type(){
        $list = Db::name("anx_type")->order('id desc')->paginate(10);
        $list = $list->toArray();
        $this->success('获取成功', $list);
    }
 
    //公告列表
    public function get_announcement_list(){
        $param = $this->request->param();
        $where = [];
        if(!empty($param['anx_type_id']) && isset($param['anx_type_id']))
        {
            $where[] = [
                ['anx_type_id', '=', $param["anx_type_id"]]
            ];
        }
        $list = Db::name("anx")->where($where)->order('id desc')
        ->paginate(10)->each(function($item){
            $item['content'] = html_entity_decode($item['content']);
            $item['content'] = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $item['content']);
            if(!empty($item["create_time"])){
                $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
            }else{
                $item["create_time"] = "";
            }
            return $item;
        });
        $list = $list->toArray();
        $this->success('获取成功', $list);
    }

    //公告详情
    public function anx_detail(){
        $param = $this->request->param();
        if (empty($param['anx_id'])) {
            $this->error('参数错误');
        }
        //增加浏览量
        Db::name("anx")->where("id",$param["anx_id"])->inc("page_view",1)->update();
        $list = Db::name("anx")->where("id",$param["anx_id"])->find();
        $list['content'] = html_entity_decode($list['content']);
        $list['content'] = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $list['content']);
        if(!empty($list["create_time"])){
            $list["create_time"] = date("Y-m-d H:i:s",$list["create_time"]);
        }else{
            $list["create_time"] = "";
        }
        $this->success('获取成功', $list);
    }    

    //首页产品列表
    public function listof_influencers_list(){
        //$param = $this->request->param();
        // $where = [];
        // if(!empty($param['title']) && isset($param['title']))
        // {
        //     $where[] = [
        //         ['title', 'like', '%'.$param['title'].'%']
        //     ];
        // }
        $list = Db::name("classification")->order('sort asc')
            ->field("id,title,sort")
            ->paginate(10)->each(function($item){
                $goods = Db::name("goods")->where("class_id",$item["id"])->field("id,title,img")->select();
                $item["goods"]= $goods;
                return $item;
            });
        $this->success('获取成功', $list);
    }

    //用户提现申请
    public function user_cashout(){
        $param = $this->request->param();
        //1微信  2支付宝
        if (empty($param['type'])) {
            $this->error('类型不能为空');
        }
        if (empty($param['account_number']) || empty($param['username']) || empty($param['img']) || empty($param['money'])) {
            $this->error('参数不能为空');
        }
        $user = Db::name("user")->where("id",$this->uid)->find();
        if($user["commission" ] < $param['money']){
            $this->error('余额不足');
        }
        Db::name("user_cashout")->insert([
            "uid"=>$this->uid,
            "type"=>$param["type"],
            "account_number"=>$param["account_number"],
            "username"=>$param["username"],
            "reamks"=>$param["reamks"],
            "img"=>$param["img"],
            "money"=>$param["money"],
            "create_time"=>time(),
        ]);
        $this->success('提交成功');
    }
 
    //分享绑定上级
    public function scan_code_binding(){
        $param = $this->request->param();
        if (empty($param['fid'])) {
            $this->error('上级id不能为空');
        }
        $user = Db::name("user")->where("id",$param["fid"])->where("is_check",1)->find();
        if(empty($user)){
            $this->error('分销商不存在');
        }
        //查询用户是否是分销商
        $smuser = Db::name("user")->where("id",$this->uid)->find();
        if($smuser["is_check"] != 1){
            Db::name("user")->where("id",$this->uid)->update(["pid"=>$param['fid']]);
        }
        $this->success('绑定成功');
    }

    //分销商申请
    public function applyfor_distributor(){
        $param = $this->request->param();
        if (empty($param['real_name'])) {
            $this->error('真实姓名不能为空');
        }
        if (empty($param['province']) || empty($param['city']) || empty($param['area'])) {
            $this->error('参数错误');
        }
        $flag = Db::name("applyfor_distributor")->where("uid",$this->uid)->find();
        if (!empty($flag)) {
            $this->error('已申请不能重复申请');
        }
        Db::name("applyfor_distributor")->insert([
            "uid"=>$this->uid,
            "real_name"=>$param["real_name"],
            "province"=>$param["province"],
            "city"=>$param["city"],
            "area"=>$param["area"],
            "reason"=>$param["reason"],
            "create_time"=>time(),
        ]);
        $this->success('提交成功');
    }
    
    //提现记录
    public function withdrawal_records(){
        $list = Db::name("user_cashout")->where("uid",$this->uid)->order("id desc")->paginate(10);
        $this->success('获取成功',$list);

    }

    //产品详情
    public function goods_detail(){
        $param = $this->request->param();
        if (empty($param['gid'])) {
            $this->error('产品id不能为空');
        }
        $list = Db::name("goods")->where("id",$param["gid"])->find();
        $list["create_time"] = date("Y-m-d H:i:s",$list["create_time"]);
        $this->success('获取成功',$list);
    }

    //分销商详情
    public function applyfordetail(){
        $list = Db::name("applyfor_distributor")->where("uid",$this->uid)->find();
        $this->success('获取成功',$list);
    }

    //二维码是否使用
    public function goods_qrcode_user(){
        $param = $this->request->param();
        if (empty($param['gid'])) {
            $this->error('产品id不能为空');
        }
        $flag = Db::name("goods_qrcode_user")->where("uid",$this->uid)->find();
        if (!empty($flag)) {
            if ($flag["status"] == 1 || $flag["status"] == 2) {
                $this->error('二维码已使用或已过期');
            }else{
                $this->success('可以使用');
            }
        }
        //获取当前时间
        $currentTime = date('Y-m-d H:i:s');
        //获取10分钟后的时间
        $futureTime = date('Y-m-d H:i:s', strtotime('+10 minutes', strtotime($currentTime)));
        Db::name("goods_qrcode_user")->insert([
            "uid"=>$this->uid,
            "gid"=>$param["gid"],
            "collection_time"=>time(),
            "failure_time"=>strtotime($futureTime),
        ]);
        $this->success('查看成功');
    }

    //二维码使用
    public function qrcodesy(){
        $param = $this->request->param();
        if (empty($param['gid'])) {
            $this->error('产品id不能为空');
        }
        Db::name("goods_qrcode_user")->where("uid",$this->uid)->where("gid",$param['gid'])->update(["usetime"=>time(),"status"=>1]);
        $this->success('操作成功');
    }

    //会员等级
    public function membership_level(){
        $list = Db::name("membership_level")->order("id desc")->select();
        $this->success('获取成功',$list);
    }

    //获取用户信息
    public function getuser_information(){
        $list = Db::name("user")->where("id",$this->uid)->find();
        $this->success('获取成功',$list);
    }

    //修改用户信息
    public function modify_user_information(){
        $param = $this->request->param();
        Db::name("user")->where("id",$this->uid)->update($param);
        $this->success('修改成功');
    }

    //配置数据
    public function config_data(){
        $user_agreement = sysconfig('sitepw','user_agreement');
        $contact_phone = sysconfig('site','contact_phone');
        $contact_whect = sysconfig('site','contact_whect');
        $qrcode_image = sysconfig('site','qrcode_image');
        $user_agreement = html_entity_decode($user_agreement);
        $user_agreement = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $user_agreement);

        // $contact_phone = html_entity_decode($contact_phone);
        // $contact_phone = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $contact_phone);

        $list = [
            "user_agreement"=>$user_agreement,
            "contact_phone"=>$contact_phone,
            "contact_whect"=>$contact_whect,
            "qrcode_image"=>$qrcode_image,
        ];
        $this->success('获取成功',$list);
        
    }



    
   
    // //经纬度转地址
    // public function let_transfer_address(){
    //     $param = $this->request->param();
    //     if (empty($param['location'])) {
    //         $this->error('参数不合法');
    //     }
    //     if (empty($param['key'])) {
    //         $this->error('参数不合法');
    //     }
    //     $method = 'GET';
    //     $url = 'https://apis.map.qq.com/ws/geocoder/v1?key='.$param['key'].'&location='.$param["location"];
    //     $header = [
    //         'Content-Type:application/json;charset=UTF-8'
    //     ];
    //     $res = [];
    //     $data = $this->http_curl($url,$method, $res, $header, $timeout = 10);
    
    //     if(!empty($data) && isset($data) && $data['status'] ==0 && $data['message'] == 'Success' )
    //     {
    //         $this->success('获取成功',$data);
    //     }else{
    //         $this->error('获取失败');
    //     }

    // }

    // public function test(){
    //     $order = Db::name("order")->where("id",1)->find();
    //     $user = Db::name("user")->where("id",$order["uid"])->find();
    //     if($user["is_mermber"] != 1){
    //          //修改用户余额
    //          Db::name("user")->where("id",$order["uid"])->inc("balance",$order["payable_money"])->update();
    //          Db::name("user")->where("id",$order["uid"])->update(["is_mermber"=>1,"level"=>$order["level"]]);
    //     }else{
    //         //分销商佣金比例
    //         $one_bili = bcdiv(sysconfig("commissoin","one_bili"),100,2);
    //         $two_bili = bcdiv(sysconfig("shopfx","two_bili"),100,2);
    //         //查询上一级
    //         if(!empty($user["pid"])){
    //             //给上一级返回佣金
    //             $puser = Db::name("user")->where("id",$user["pid"])->find();
    //             $user_commission = bcmul($one_bili,$order["paidin_money"],2);
    //             Db::name("user")->where("id",$user["pid"])->inc("commission",$user_commission)->update();
    //             //加入记录
    //             Db::name("user_commrecord")->insert([
    //                 "oid"=>$order["id"],
    //                 "uid"=>$order["uid"],
    //                 "pid"=>$user["pid"],
    //                 "user_commoney"=>$puser["commission"],
    //                 "return_commission"=>$user_commission,
    //                 "create_time"=>time()
    //             ]);
    //         }
    //         //给上二级返回佣金
    //         $pyiuser = Db::name("user")->where("id",$user["pid"])->find();
    //         $pyiuser_commission = bcmul($two_bili,$order["paidin_money"],2);
    //         if(!empty($pyiuser["pid"])){
    //             Db::name("user")->where("id",$pyiuser["pid"])->inc("commission",$pyiuser_commission)->update();
    //             //加入记录
    //             Db::name("user_commrecord")->insert([
    //                 "oid"=>$order["id"],
    //                 "uid"=>$order["uid"],
    //                 "pid"=>$pyiuser["pid"],
    //                 "user_commoney"=>$pyiuser["commission"],
    //                 "return_commission"=>$pyiuser_commission,
    //                 "create_time"=>time()
    //             ]);
    //         }
          
    //         dump(1111);die;


    //     }
    // }


    public function getsing(){
       // md5("apikey=123&timestamp=232&username=2323")
        //$apikey = strtolower("LNeFR3pl2qm5j4z8p83D");
        $apikey = "LNeFR3pl2qm5j4z8p83D";
        $time = date("YmdHis");
        dump($time);
        $sing = "apikey=$apikey&timestamp=$time&username=99958724";
        dump(md5($sing));die;
        // 分割字符串为单词数组
        // $words = explode("&", $sing);
        // // 对单词数组进行排序
        // sort($words);
        // // 拼接排序后的单词数组为字符串
        // $sortedStr = implode("&", $words);
        //dump($sortedStr);die; 
       
    }


    public function hftesty(){
        //接口类型：互亿无线手机话费充值接口。
        // 账户注册：请通过该地址开通账户https://user.ihuyi.com/register.html
        $basicUrl = "http://api.ihuyi.com/f/phone?action=recharge&%s";
        $username = '99958724';
        $apikey = 'LNeFR3pl2qm5j4z8p83D';
        $mobile = '18502930835';
        $package = 1;//套餐数额
        $orderid = 'TEST_'.date("YmdHis").mt_rand(100, 1000);//订单号
        $timestamp = date("YmdHis");
        $dataGet = array();
        $dataGet['package'] = $package;
        $dataGet['username'] = $username;
        $dataGet['timestamp'] = $timestamp;
        $dataGet['mobile'] = $mobile;
        $dataGet['orderid'] = $orderid;
        $dataGet['sign'] = md5("apikey=$apikey&mobile=$mobile&orderid=$orderid&package=$package&timestamp=$timestamp&username=$username");
        foreach ($dataGet as $key => $row) {
            $dataReturn[] = sprintf("%s=%s", $key, $row);
        }
        $urlGet = sprintf($basicUrl, implode("&", $dataReturn));
        $ch = \curl_init();
        curl_setopt($ch, CURLOPT_URL, $urlGet); //定义表单提交地址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //60秒
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_REFERER, 'http://' . $_SERVER['HTTP_HOST']);
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($ch);
        $curlError = curl_error($ch);
        curl_close($ch);
        $dataRet = json_decode($data, 1);
        dump($dataRet);die;
        if ($dataRet['code'] == 1) {
        //提交成功
            $this->success("提交成功",$dataRet['taskid']);
        } else {
            $this->error("提交失败");
        }
    }

    //余额查询
    // public function yuechx(){
    //     $basicUrl = "http://api.ihuyi.com/f/basic?action=getbalance&%s";
    //     $username = '99958724';
    //     $apikey = 'LNeFR3pl2qm5j4z8p83D';
    //     $timestamp = date("YmdHis");
    //     $dataGet = array();
    //     $dataGet['username'] = $username;
    //     $dataGet['timestamp'] = $timestamp;
    //     $dataGet['sign'] = md5("apikey=$apikey&timestamp=$timestamp&username=$username");
    //     foreach ($dataGet as $key => $row) {
    //         $dataReturn[] = sprintf("%s=%s", $key, $row);
    //     }
    //     $urlGet = sprintf($basicUrl, implode("&", $dataReturn));
    //     $ch = \curl_init();
    //     curl_setopt($ch, CURLOPT_URL, $urlGet); //定义表单提交地址
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //     curl_setopt($ch, CURLOPT_TIMEOUT, 30); //60秒
    //     curl_setopt($ch, CURLOPT_HEADER, 0);
    //     curl_setopt($ch, CURLOPT_REFERER, 'http://' . $_SERVER['HTTP_HOST']);
    //     curl_setopt($ch, CURLOPT_POST, 0);
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //     $data = curl_exec($ch);
    //     $curlError = curl_error($ch);
    //     curl_close($ch);
    //     $dataRet = json_decode($data, 1);
    //    // dump($dataRet);die;
    //     if ($dataRet['code'] == 1) {
    //     //提交成功
    //         $this->success("提交成功",$dataRet['balance']);
    //     } else {
    //         $this->error("提交失败");
    //     }
    // }

    //获取话费包档位
    public function getpackages(){
        $basicUrl = "http://api.ihuyi.com/f/phone?action=getpackages&%s";
        $username = '99958724';
        $apikey = 'LNeFR3pl2qm5j4z8p83D';
        $timestamp = date("YmdHis");
        $dataGet = array();
        $dataGet['username'] = $username;
        $dataGet['timestamp'] = $timestamp;
        $dataGet['sign'] = md5("apikey=$apikey&timestamp=$timestamp&username=$username");
        foreach ($dataGet as $key => $row) {
            $dataReturn[] = sprintf("%s=%s", $key, $row);
        }
        $urlGet = sprintf($basicUrl, implode("&", $dataReturn));
        $ch = \curl_init();
        curl_setopt($ch, CURLOPT_URL, $urlGet); //定义表单提交地址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //60秒
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_REFERER, 'http://' . $_SERVER['HTTP_HOST']);
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($ch);
        $curlError = curl_error($ch);
        curl_close($ch);
        $dataRet = json_decode($data, 1);
       // dump($dataRet);die;
        if ($dataRet['code'] == 1) {
        //提交成功
            $this->success("提交成功",$dataRet['packages']);
        } else {
            $this->error("提交失败");
        }
   }
 
    //  //上传图片
    //  public function upload()
    //  {
    //      $file = request()->file('file');
    //      if (empty($file)) {
    //          $this->error('请选择上传文件');
    //      }
    //      try {
    //          validate('app\api\validate\Upload')
    //              ->scene('img')
    //              ->check(['file' => $file]);
    //          $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
    //          $url = request()->domain() . '/' . $savename;
    //          $this->success('上传成功',$url);
    //      } catch (\think\exception\ValidateException $e) {
    //          $this->error('上传失败',$e->getMessage());
    //      }
    //  }
     
    
    //  //修改用户信息
    //  public function modify_user_information(){
    //     $param = $this->request->param();
    //     if(empty($param['nickname'])){
    //         $this->error('昵称不能为空');
    //     }
    //     if(empty($param['avatar'])){
    //         $this->error('头像不能为空');
    //     }
    //     if(empty($param['gender'])){
    //         $this->error('性别不能为空');
    //     }
    //     Db::name("user")->where("id",$this->uid)->update($param);
    //     $this->success('修改成功');
    //  }

    //  //配置数据
    //  public function config_data(){
    //     $param = $this->request->param();
    //     if(empty($param['type'])){
    //         $this->error('类型不能为空');
    //     }
    //     if($param["type"] == 1){
    //         $service_agreement = sysconfig('contact','service_agreement');
    //         $service_agreement = html_entity_decode($service_agreement);
    //         $data = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $service_agreement);
    //     }elseif($param["type"] == 2){
    //         $data = sysconfig('site','contact_phone');
    //     }else{
    //         $this->error('类型不存在');
    //     }
    //     $this->success('获取成功', $data);
    //  }
 



     
        






















     

     

    
 
   
}
